#include "App.h"

App::App()
{
	//this->taskTable = nullptr;
}

App::~App()
{
	/*if(this->taskTable!= nullptr)
	{
		delete [] this->taskTable;
	}*/
}


bool App::ReadFile(std::string fileName)
{
	bool ret =false;

	std::ifstream file(fileName.c_str());

	if(file.is_open())
	{
		
		ret = true;
		file >> this->tasksCount;
		file >> this->machines;
		this->size = machines*tasksCount+1;

		this->taskTable = new Task* [size+1]();
		for(int i = 0;i<size+1;i++)
		{
				this->taskTable[i] = new Task();
		}
	
		int  tmp = 0;
		file>>tmp;
		int counter = 1;
		
		for(int i = 1; i <=this->tasksCount; i ++)
		{
			file>>tmp;

			for(int j =1;j <=this->machines; j++)
			{
				file >> this->taskTable[counter]->m;
				file >> this->taskTable[counter]->t;
				this->taskTable[counter]->id = counter;
				
				if(j!=1)
				{
					this->taskTable[counter]->pred = this->taskTable[counter-1];	
				}
				else
				{
					this->taskTable[counter]->pred = nullptr;
				}

				if(j+1<=this->machines)
				{
					this->taskTable[counter]->next = this->taskTable[counter+1];
				}
				else
				{
					this->taskTable[counter]->next = nullptr;
				}
				counter++;
			}
		}

		file.close();
	}

	return ret;
}

void App::Start(std::string fileName)
{
	

	Algorithm *algorithm = nullptr;

	if(ReadFile(fileName))
	{
#if 0
		Task *t;
		for(int i = 1;i <this->size;i++)
		{
			std::cout<<this->taskTable[i]->id<<" : "<<std::endl;
			t = taskTable[i]->next;
			while(t!=nullptr)
			{
				std::cout<<t->id<<" ";
				t = t->next;
			}
			std::cout<<std::endl;
			std::cout<<std::endl;
		}
		std::cout<<"od tylu:"<<std::endl;
		for(int i = this->size-1;i>=1;i--)
		{
			std::cout<<this->taskTable[i]->id<<" : "<<std::endl;
			t = taskTable[i]->pred;
			while(t!=nullptr)
			{
				std::cout<<t->id<<" ";
				t = t->pred;
			}
			std::cout<<std::endl;
			std::cout<<std::endl;
		}
#endif
		algorithm = new Algorithm(this->taskTable,this->size,this->tasksCount,this->machines);
		algorithm->Do();

#ifdef _DEBUG
		//insa->Permutation();
#endif
		//std::cout<<"File: "<<fileName<<" Cmax:"<<insa->CMax()<<std::endl;
	}

	if(algorithm!=nullptr)
	{
		delete algorithm;
	}
}